﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sherwood.Mvc
{
    public static class StringExtensions
    {
        /// <summary>
        /// Replaces occurances of [Key] in the string with the corrosponding value
        /// in the parameters dictionary
        /// </summary>
        /// <param name="input"></param>
        /// <param name="parameters"></param>
        /// <returns></returns> 
        public static string Parameterize(this string input, Dictionary<string,string> parameters)
        {
            StringBuilder sb = new StringBuilder(input);
            if (parameters != null)
            {
                foreach (string key in parameters.Keys)
                {
                    sb.Replace("[" + key + "]", parameters[key]);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// Replaces all occurances of [PropertyName] in the string with the corrosponding
        /// property values found on the object(s) passed in.
        /// If multiple objects are passed in with the same property names, the value of the 
        /// first object with a matching property is used.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Parameterize(this string input, params object[] obj)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            if (obj.Length == 1 && obj[0] != null)
            {
                parameters = obj[0].ToPropertyStringDictionary();
            }
            else
            {
                foreach (object o in obj)
                {
                    if (o != null)
                    {
                        var objectParameters = o.ToPropertyStringDictionary();
                        foreach (string key in objectParameters.Keys)
                        {
                            if (!parameters.ContainsKey(key))
                            {
                                parameters[key] = objectParameters[key];
                            }
                        }
                    }
                }
            }

            return Parameterize(input,parameters);
        }

    }
}
